package lcof;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MinSubArrayLen209 {
    public int minSubArrayLen(int target, int[] nums) {
        Arrays.sort(nums);
        int count = 0;
        int res = 0;
        for (int i = nums.length - 1; i >= 0; i--) {
            res++;
            count += nums[i];
            if (count >= target) {
                return res;
            }
        }
        return 0;
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i <nums.length-2; i++) {
            //相同的起点不需要重复统计
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            //从i右边开始，左右指针
            int l = i + 1, r = nums.length - 1;
            int target = -nums[i];
            while (l < r) {
                int num =  nums[l] + nums[r];
                if (num == target) {
                    //相同的起点不需要重复统计
                    if (l > i + 1 && nums[l - 1] == nums[l]) {
                        l++;
                        r--;
                        continue;
                    }
                    result.add(Arrays.asList(nums[i], nums[l], nums[r]));
                    l++;
                    r--;
                } else if (num < target) {
                    //需要更大的值
                    l++;
                } else {
                    //需要减少值
                    r--;
                }
            }
        }
        return result;
    }
}
